package com.zxlspace.collection2.map;


import java.util.*;

/***
 * 根据hashmap分拣思路，计算每个班级学生的平均分
 */
public class TestAvgScoreByClass {

    public static void main(String[] args) {
        //考试
        List<Student> list = exam();

        //分析成绩

        Map<String, ClassRoom> classRoomMap = analyze(list);
        System.out.println(classRoomMap);
        //打印成绩
        view(classRoomMap);
    }

    /**
     * 查看每个班的总分和平均分  -->遍历 map
     */
    public static void view(Map<String,ClassRoom> map){
        Set<String> keys =map.keySet();
        //获取迭代器对象
        Iterator<String> keysIt =keys.iterator();
        //先判断
        while(keysIt.hasNext()){
            //再获取
            String no =keysIt.next();
            ClassRoom room =map.get(no);
            //查看总分  计算平均分
            double total =room.getTotalScore();
            double avg =total/room.getStudentList().size();
            System.out.println(no+"-->"+total+"-->"+avg);
        }
    }

    public static  Map<String, ClassRoom> analyze( List<Student> list) {
        Map<String, ClassRoom> map = new HashMap<>();
       /* ClassRoom classRoom = null;
        for (Student student : list) {
            if (!map.containsKey(student.getClassNo())) {
                classRoom = new ClassRoom(student.getClassNo());
                classRoom.getStudentList().add(student);
                map.put(student.getClassNo(), classRoom);
            }else {
                classRoom = map.get(student.getClassNo());
                classRoom.getStudentList().add(student);
            }
            classRoom.setTotalScore( classRoom.getTotalScore()+student.getScore());
        }*/

        for (Student student : list) {
            String no = student.getClassNo();
            double score = student.getScore();
            ClassRoom classRoom = map.get(no);
            if (null == classRoom) {
                classRoom = new ClassRoom(no);
                map.put(no, classRoom);
            }

            classRoom.getStudentList().add(student);
            classRoom.setTotalScore(classRoom.getTotalScore() + score);  //计算总分
        }
        return map;
    }

    public static List<Student> exam() {
        List<Student> list = new ArrayList<>();
        //存放学生成绩
        list.add(new Student("老裴","a",85));
        list.add(new Student("裴兜兜","a",86));
        list.add(new Student("裴裴","a",89));
        list.add(new Student("高小三","b",80));
        list.add(new Student("高高","b",80));
        return list;
    }
}
